/*
Pyxis 2.0
Copyright 2010-2011 Thomas W. Holtquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Collections;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Skewworks.Pyxis.EXT;
using Skewworks.Pyxis.Kernel;

namespace Skewworks.Pyxis.GUI.Controls
{

    [Serializable]
    public class Scrollbar : Control
    {

        #region Variables

        private bool _gDown = false;
        private int _min;
        private int _max;
        private int _val;
        private int _sml = 1;
        private int _lrg = 10;
        private Orientation _orientation;

        private rect _decRect;
        private rect _incRect;
        private rect _grpRect;
        private int _chgVal;
        private Thread _changer;

        private int _mY = 0;
        private int _mX = 0;

        private bool _auto;

        #endregion

        #region Constructors

        public Scrollbar(int x, int y, int size, Orientation orientation)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = 0;
            _max = 100;
            _val = 0;
        }

        public Scrollbar(int x, int y, int size, Orientation orientation, int Minimum, int Maximum)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = Minimum;
            _max = Maximum;
            _val = 0;
        }

        public Scrollbar(int x, int y, int size, Orientation orientation, int Minimum, int Maximum, int value)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = Minimum;
            _max = Maximum;
            _val = value;
        }

        #endregion

        #region Events

        public event OnValueChanged ValueChanged;

        /// <summary>
        /// Event for Taps
        /// </summary>
        /// <param name="sender"></param>
        protected virtual void OnValueChanged(Object sender, int value)
        {
            if (ValueChanged != null) ValueChanged(sender, value);
        }

        #endregion

        #region Touch Invokes

        public override void TouchDown(object sender, point e)
        {
            _mDown = true;

            if (!_enabled) return; 
            if (_decRect.contains(e))
            {
                Value = _val - _sml;
                _chgVal = -_sml;
                if (_auto)
                {
                    _changer = new Thread(AutoIncDec);
                    _changer.Priority = ThreadPriority.AboveNormal;
                    _changer.Start();
                }
                return;
            }

            if (_incRect.contains(e))
            {
                Value = _val + _sml;
                _chgVal = _sml;
                if (_auto)
                {
                    _changer = new Thread(AutoIncDec);
                    _changer.Priority = ThreadPriority.AboveNormal;
                    _changer.Start();
                }
                return;
            }

            if (_grpRect.contains(e))
            {
                _mX = e.X;
                _mY = e.Y;
                _gDown = true;
                return;
            }

            if (_orientation == Orientation.Horizontal)
            {
                Value = _val + ((e.X < _grpRect.X) ? -_lrg : _lrg);
            }
            else
            {
                Value = _val + ((e.Y < _grpRect.Y) ? -_lrg : _lrg);
            }

        }

        public override void TouchUp(object sender, point e)
        {
            if (_mDown)
            {
                if (this.ScreenBounds.contains(e)) OnTap(this, new point(e.X - Left, e.Y - Top));
                _mDown = false;
            }
            _gDown = false;
        }

        public override void TouchMove(object sender, point e)
        {
            // Only respond if we have the gripper
            if (!_gDown) return;

            if (_orientation == Orientation.Horizontal)
            {
                // Calculate value from New Position
                // Difference (DIF)         = current X - initial X
                // New X (NWX)              = (GripX + DIF) - left - 16 (remove offset left & dec CommandButton)
                // Slide Range (ASR)        = Width - 32 - GripWidth (32 for both CommandButtons)
                // Percent of Slide (PoS)   = NWX / ASR
                // value (VAL)              = ((max - min) * PoS) + min
                Value = (int)((_max - _min) * ((float)((_grpRect.X + (e.X - _mX)) - Left - 16) / (float)(_w - 32 - _grpRect.Width))) + _min;
            }
            else
            {
                // Calculate value from New Position
                // Difference (DIF)         = current Y - initial Y
                // New Y (NWY)              = (GripY + DIF) - top - 16 (remove offset top & dec CommandButton)
                // Slide Range (ASR)        = Height - 32 - GripHeight (32 for both CommandButtons)
                // Percent of Slide (PoS)   = NWY / ASR
                // value (VAL)              = ((max - min) * PoS) + min
                Value = (int)((_max - _min) * ((float)((_grpRect.Y + (e.Y - _mY)) - Top - 16) / (float)(_h - 32 - _grpRect.Height))) + _min;
            }

            _mX = e.X;
            _mY = e.Y;
        }

        #endregion

        #region  Properties

        public bool AutoRepeating
        {
            get { return _auto; }
            set { _auto = value; }
        }

        public int Minimum
        {
            get { return _min; }
            set
            {
                if (value >= _max) value = _max - 1;
                _min = value;
                Render(true);
            }
        }

        public int Maximum
        {
            get { return _max; }
            set
            {
                if (value <= _min) value = _min + 1;
                _max = value;
                Render(true);
            }
        }

        public int Value
        {
            get { return _val; }
            set
            {
                if (value < _min) value = _min;
                if (value > _max) value = _max;
                if (_val == value)
                    return;
                _val = value;
                Render(true);
                OnValueChanged(this, _val);
            }
        }

        public int SmallChange
        {
            get { return _sml; }
            set
            {
                if (_sml == value) return;
                _sml = value;
                Render(true);
            }
        }

        public int LargeChange
        {
            get { return _lrg; }
            set
            {
                if (_lrg == value) return;
                _lrg = value;
                Render(true);
            }
        }

        public override int Width
        {
            get
            {
                return _w;
            }
            set
            {
                ;
            }
        }

        public override int Height
        {
            get { return _h; }
            set
            {
                ;
            }
        }
        
        #endregion

        #region GUI

        public override void Render(bool flush)
        {
            if (_parent == null || _parent.ScreenBuffer == null || !_visible || _suspend) return;

            int iGripSize = 0;

            // Set clipping region in case we're off parent somewhere (can happen w/ scroll)
            _parent.ScreenBuffer.SetClippingRectangle(_parent.Left, _parent.Top, _parent.Width, _parent.Height);

            // Background is the same regardless of orientation
            _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left, Top, _w, _h, 0, 0, Colors.Gray, 0, 0, Colors.Gray, 0, 0, 256);

            if (_orientation == Orientation.Horizontal)
            {
                // Draw the Left/Right CommandButtons
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left, Top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(Left + 4, Top + 4, Resources.GetBitmap(Resources.BitmapResources.left), 0, 0, 5, 9);
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left + _w - 16, Top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(Left + _w - 11, Top + 4, Resources.GetBitmap(Resources.BitmapResources.right), 0, 0, 5, 9);

                if (_enabled)
                {
                    // Update Rects
                    // We do this every render incase our offset has changed
                    _decRect = new rect(Left, Top, 16, 16);
                    _incRect = new rect(Left + _w - 16, Top, 16, 16);

                    // Calculate Gripper Size
                    // Total Value Range (TVR)      = max - min
                    // Total Travel Range (TTR)     = TVR / SmallChange
                    // Available Grip Range (AGR)   = Size - 32
                    // Grip Size                    = AGR - TTR
                    iGripSize = (_w - 32) - ((_max - _min) / _sml);
                    if (iGripSize < 8) iGripSize = 8;

                    // Calculate Gripper left (remember we might change gripper size to meet minimum)
                    // Available Draw Range (ADR)   = (Size - 32 - GripSize)
                    // Percent of Total (PoT)       = (value - min) / (max - min)
                    // Offset                       = ADR * PoT
                    int iOffset = (int)((_w - 32 - iGripSize) * ((float)(_val - _min) / (float)(_max - _min)));

                    // Draw the Gripper
                    _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, iOffset + Left + 16, Top, iGripSize, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                    _grpRect = new rect(iOffset + Left + 16, Top, iGripSize, 16);
                }
            }
            else
            {
                // Draw the Up/Down CommandButtons
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left, Top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(Left + 4, Top + 5, Resources.GetBitmap(Resources.BitmapResources.up), 0, 0, 9, 5);
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left, Top + _h - 16, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(Left + 4, Top + _h - 11, Resources.GetBitmap(Resources.BitmapResources.down), 0, 0, 9, 5);

                if (_enabled)
                {
                    // Update Rects
                    // We do this every render incase our offset has changed
                    _decRect = new rect(Left, Top, 16, 16);
                    _incRect = new rect(Left, Top + _h - 16, 16, 16);

                    // Calculate Gripper Size
                    // Total Value Range (TVR)      = max - min
                    // Total Travel Range (TTR)     = TVR / SmallChange
                    // Available Grip Range (AGR)   = Size - 32
                    // Grip Size                    = AGR - TTR
                    iGripSize = (_h - 32) - ((_max - _min) / _sml);
                    if (iGripSize < 8) iGripSize = 8;

                    // Calculate Gripper left (remember we might change gripper size to meet minimum)
                    // Available Draw Range (ADR)   = (Size - 32 - GripSize)
                    // Percent of Total (PoT)       = (value - min) / (max - min)
                    // Offset                       = ADR * PoT
                    int iOffset = (int)((_h - 32 - iGripSize) * ((float)(_val - _min) / (float)(_max - _min)));

                    // Draw the Gripper
                    _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, Left, iOffset + Top + 16, 16, iGripSize, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                    _grpRect = new rect(Left, iOffset + Top + 16, 16, iGripSize);
                }
            }

            if (flush)
            {
                _parent.ScreenBuffer.Flush(Left, Top, _w, _h);
                _parent.ScreenBuffer.SetClippingRectangle(0, 0, AppearanceManager.ScreenWidth, AppearanceManager.ScreenHeight);
            }
        }

        #endregion

        #region Private Methods

        private void AutoIncDec()
        {
            int iWait = 750;
            while (_mDown)
            {
                Thread.Sleep(iWait);
                if (!_mDown) return;
                Value = _val + _chgVal;
                switch (iWait)
                {
                    case 750:
                        iWait = 500;
                        break;
                    case 500:
                        iWait = 250;
                        break;
                    case 250:
                        iWait = 75;
                        break;
                }
            }
        }

        #endregion

    }

}
